<template>
  <div>
    <section
      class="message"
      :class="showSelBox > 0 ? 'message-bottom-collapse' : 'message-bottom'"
    >
      <van-pull-refresh v-model="loading" ref="loadmore" @refresh="onRefresh">
        <p class="more" v-if="messages.length == 0">
          <span v-if="!loading">下拉刷新</span>
        </p>
        <van-list v-model="loading" :finished="!loading">
          <van-cell v-for="item in messages" :key="item.Id" :border="false">
            <p class="time" v-if="item.ShowTime">
              <span v-text="item.CreateTime"></span>
            </p>
            <p class="time system" v-if="item.Type == 10000">
              <span v-html="item.Text"></span>
            </p>
            <div
              :class="'main' + (item.CreatorId === userInfo.Id ? ' self' : '')"
              v-else
            >
              <van-image
                class="avatar"
                width="39"
                height="39"
                alt="avatar"
                radius="5"
                :src="item.Avatar | AvatarFilter"
              />
              <!-- 文本 -->
              <!-- <div class="text" v-emotion="item.Text" v-if="item.type == 1"></div> -->
              <!-- <div class="text" v-if="item.Type == 1">{{ item.Text }}</div> -->

              <div
                class="text"
                ref="content"
                v-html="toEmotion(item.Text)"
                v-if="item.Type == 1"
              ></div>

              <!-- 图片 -->
              <div class="text" v-else-if="item.Type == 2">
                <img
                  :src="item.Text"
                  class="image"
                  controls="controls"
                  alt="图片"
                  @click="handleEvent(item)"
                />
              </div>

              <!-- 视频 -->
              <div class="text" v-else-if="item.Type == 3">
                <video
                  :src="item.Text"
                  class="image"
                  controls="controls"
                  alt="视频"
                  @click="handleEvent(item)"
                />
              </div>

              <!-- 录音 -->
              <div class="text" v-else-if="item.Type == 4">
                <audio
                  :src="item.Text"
                  class="image"
                  controls="controls"
                  alt="语音"
                  @click="handleEvent(item)"
                />
              </div>

              <!-- 文件 -->
              <div class="text" v-else-if="item.Type == 5">
                <c-upload-file
                  v-model="item.Text"
                  :maxCount="1"
                  class="image"
                  disabled
                ></c-upload-file>
              </div>

              <!-- 红包 -->
              <div class="text" v-else-if="item.Type == 6">
                <img :src="item.Text" class="image" alt="红包" />
              </div>

              <!-- 其他 -->
              <div
                class="text"
                v-else-if="item.Type != 10000"
                v-text="
                  '[暂未支持的消息类型:' + item.Type + ']\n\r' + item.Text
                "
              ></div>
            </div>
          </van-cell>
        </van-list>
      </van-pull-refresh>
    </section>
    <div class="foot">
      <van-field
        id="txtContent"
        placeholder="请输入消息"
        class="content"
        ref="txtContent"
        :autofocus="true"
        v-model="contentText"
        @keyup.enter="sendText"
      />
      <span class="btn-face" v-on:click="showSelBox = showSelBox == 1 ? 0 : 1"
        ><van-icon name="smile-o"
      /></span>
      <span class="btn-plus" v-on:click="showSelBox = showSelBox == 2 ? 0 : 2"
        ><van-icon name="add-o"
      /></span>
      <section class="selbox" :class="showSelBox > 0 ? 'show' : 'hide'">
        <section v-show="showSelBox == 1" class="face-box">
          <div class="emjioBox">
            <ul class="emjio">
              <li
                v-for="item in Object.keys(emoji)"
                :key="item"
                @click="selectEmit(item)"
              >
                <a
                  v-if="emoji[item] && emoji[item].position"
                  :style="emojiStyle(item)"
                ></a>
                <a v-else-if="emoji[item].length < 5">{{ emoji[item] }}</a>
                <img v-else :src="require('@/images' + emoji[item])" />
              </li>
            </ul>
          </div>
        </section>
        <div v-show="showSelBox == 2">
          <span class="btn-icon" v-on:click="bindButton('img')"
            ><van-icon name="photo-o"
          /></span>
          <span class="btn-icon" v-on:click="bindButton('video')"
            ><van-icon name="video-o"
          /></span>
          <span class="btn-icon" v-on:click="bindButton('audio')"
            ><van-icon name="music-o"
          /></span>
          <span class="btn-icon" v-on:click="bindButton('file')"
            ><van-icon name="orders-o"
          /></span>
          <input
            type="file"
            ref="refImg"
            style="display:none"
            accept="image/jpg, image/png, image/jpeg, image/gif"
            v-on:change="fileOnload"
          />
          <input
            type="file"
            ref="refVideo"
            style="display:none"
            accept="audio/mp4, video/mp4"
            v-on:change="fileOnload"
          />
          <input
            type="file"
            ref="refAudio"
            style="display:none"
            accept="audio/mp4"
            v-on:change="fileOnload"
          />
          <input
            type="file"
            ref="refFile"
            style="display:none"
            v-on:change="fileOnload"
          />
        </div>
      </section>
    </div>
    <van-popup v-model="show">
      <img :src="imgSrc" v-if="imgSrc" style="width: 100%; object-fit: cover" />
      <video
        :src="videoSrc"
        v-if="videoSrc"
        style="width: 100%; object-fit: cover"
        controls="controls"
      ></video>
      <audio
        :src="audioSrc"
        v-if="audioSrc"
        style="width: 100%; object-fit: cover"
        controls="controls"
      ></audio>
    </van-popup>
  </div>
</template>

<script>
import emoji from "./emoji.json";
import emojiParser from "wechat-emoji-parser";
import { mapGetters } from "vuex";
import CUploadFile from "@/components/CUploadFile";
import Vue from "vue";
import { ACCESS_TOKEN } from "@/store/mutation-types";
import { ImagePreview } from "vant";
import { Form } from "vant";
const uuid = require("uuid");

export default {
  components: {
    CUploadFile
  },
  model: {
    prop: "outloading"
  },
  props: {
    messages: {
      type: Array,
      default: () => []
    },
    title: {
      type: String,
      default: ""
    },
    outloading: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      emoji,
      contentText: "",
      selectedUserId: null,
      show: false,
      imgSrc: "",
      videoSrc: "",
      audioSrc: "",
      history: false,
      showSelBox: 0, // 0隐藏 1显示表情 2显示其他
      selFace: "表情",
      selOther: "其他功能",
      loading: false
    };
  },
  mounted: function() {
    this.scrollToBottom();
    this.focusTxtContent();
  },
  methods: {
    emojiStyle(item) {
      const emojiitem = this.emoji[item];
      if (!emojiitem) return {};
      return {
        display: "inline-block",
        background: `url('/emotion/6AfH8-r.png')  no-repeat`,
        width: `28px`,
        height: `28px`,
        "background-position": emojiitem.position
      };
    },
    sendText() {
      if (this.contentText) {
        this.$emit("submit", this.contentText);
        this.contentText = "";

        this.scrollToBottom();
      }
    },
    //处理排版
    toEmotion(html) {
      return emojiParser(html).replace(
        /(<img src)/g,
        '<img data-class="iconBox" src'
      );
    },
    selectEmit(emoji) {
      this.contentText += emoji;
      this.focusTxtContent();
    },
    onRefresh() {
      this.$emit("onrefresh");
    },
    //处理事件
    handleEvent(params) {
      if (params.Type === 2) {
        // this.imgSrc = params.Text;
        // this.show = true;
        const instance = ImagePreview({
          images: [params.Text]
        });
      } else if (params.Type === 3) {
        this.videoSrc = params.Text;
        this.show = true;
      } else if (params.Type === 4) {
        this.audioSrc = params.Text;
        this.show = true;
      } else if (params.Type === 5) {
        window.open(params.Text);
      }
    },
    handleCancel() {
      this.imgSrc = undefined;
      this.videoSrc = undefined;
      this.audioSrc = undefined;
      this.show = false;
    },
    //聚焦输入框
    focusTxtContent: function() {
      this.$refs.txtContent.focus();
    },
    //滚动条滚动到底部
    scrollToBottom: function() {
      setTimeout(function() {
        var chatlist = document.getElementsByClassName("message")[0];
        chatlist.scrollTop = chatlist.scrollHeight;
      }, 100);
    },
    bindButton(type) {
      //this.tools.callback && this.tools.callback(type)
      this.type = type;
      if (this.type === "img") {
        this.$refs.refImg.dispatchEvent(new MouseEvent("click"));
      } else if (this.type === "video") {
        this.$refs.refVideo.dispatchEvent(new MouseEvent("click"));
      } else if (this.type === "audio") {
        this.$refs.refAudio.dispatchEvent(new MouseEvent("click"));
      } else if (this.type === "file") {
        this.$refs.refFile.dispatchEvent(new MouseEvent("click"));
      }
    },
    getFileName(url) {
      let reg = /^.*\/(.*?)$/;
      let match = reg.test(url);
      if (match) {
        return RegExp.$1;
      } else {
        return "";
      }
    },
    fileOnload() {
      //const file = document.getElementById('files').files[0]
      var file = null;
      if (this.type === "img") {
        file = this.$refs.refImg.files[0];
      } else if (this.type === "video") {
        file = this.$refs.refVideo.files[0];
      } else if (this.type === "audio") {
        file = this.$refs.refAudio.files[0];
      } else if (this.type === "file") {
        file = this.$refs.refFile.files[0];
      }
      var param = new FormData(); // 创建form对象
      param.append("file", file); // 通过append向form对象添加数据
      var config = {
        headers: { "Content-Type": "multipart/form-data" }
      };
      if (Vue.ls.get(ACCESS_TOKEN)) {
        config.headers.Authorization = "Bearer " + Vue.ls.get(ACCESS_TOKEN);
      }
      var url = `${this.$rootUrl}/Base_Manage/Upload/UploadFileByForm`;
      this.$http.post(url, param, config).then(res => {
        var file = {
          name: this.getFileName(res.url),
          uid: uuid.v4(),
          status: "done",
          url: res.url
        };
        // 双向绑定
        //this.$emit('emoji', file.url)
        var type = 1;
        if (this.type === "img") {
          type = 2;
        } else if (this.type === "video") {
          type = 3;
        } else if (this.type === "audio") {
          type = 4;
        } else if (this.type === "file") {
          type = 5;
        }
        this.$emit("submit", file.url, type);
      });
    }
  },
  computed: {
    ...mapGetters(["userInfo"])
  },
  watch: {
    outloading: function(newVal) {
      this.loading = newVal;
    },
    loading(val) {
      this.$emit("input", val);
    }
  }
};
</script>

<style lang="less" scoped>
.van-cell {
  background: transparent;
  padding: 3px 10px;
}

.message .more {
  margin: 10px 0;
  font-size: 16px;
  text-align: center;
}

//对话框中的样式
.message {
  position: absolute;
  top: 48px;
  bottom: 48px;
  left: 0px;
  right: 0px;
  overflow-x: hidden;
}

.message-bottom {
  bottom: 48px;
}

.message-bottom-collapse {
  bottom: 188px;
}

.message li {
  margin-bottom: 15px;
  left: 0;
  position: relative;
  display: block;
}
.message .time {
  margin: 10px 0;
  text-align: center;
}
.message .text {
  display: inline-block;
  position: relative;
  padding: 0 10px;
  max-width: calc(100% - 55px);
  min-height: 35px;
  line-height: 2.1;
  font-size: 15px;
  padding: 6px 10px;
  text-align: left;
  word-break: break-all;
  background-color: #fff;
  color: #000;
  border-radius: 4px;
  box-shadow: 0px 1px 7px -5px #000;
}
.message .avatar {
  float: left;
  margin: 0 10px 0 0;
  border-radius: 3px;
  background: #fff;
}
.message .time > span {
  display: inline-block;
  padding: 0 5px;
  font-size: 12px;
  color: #fff;
  border-radius: 2px;
  background-color: #dadada;
}
.message .system > span {
  padding: 4px 9px;
  text-align: left;
}
.message .text:before {
  content: " ";
  position: absolute;
  top: 9px;
  right: 100%;
  border: 6px solid transparent;
  border-right-color: #fff;
}
.message .self {
  text-align: right;
}
.message .self .avatar {
  float: right;
  margin: 0 0 0 10px;
}
.message .self .text {
  background-color: #9eea6a;
}

.message .self .text:before {
  right: inherit;
  left: 100%;
  border-right-color: transparent;
  border-left-color: #9eea6a;
}
.message .image {
  max-width: 200px;
}
img.static-emotion-gif,
img.static-emotion {
  vertical-align: middle !important;
}
.an-move-left {
  left: 0;
  //animation: moveLeft 0.7s ease;
  //-webkit-animation: moveLeft 0.7s ease;
}
.an-move-right {
  left: 0;
  //animation: moveRight 0.7s ease;
  //-webkit-animation: moveRight 0.7s ease;
}
.bgnone {
  background: none;
}
.foot {
  width: 100%;
  min-height: 48px;
  position: fixed;
  bottom: 0px;
  left: 0px;
  background: #f1efef;
}
.foot .content {
  position: absolute;
  display: inline-block;
  padding: 1.5vh;
  background: #fff;
  margin-top: 5px;
  margin-left: 60px;
  margin-right: 5px;
  width: calc(100% - 65px);
  height: 38px;
}

.foot .btn-plus {
  position: absolute;
  margin-top: 10px;
  margin-left: 30px;
  font-size: 0.75rem;
}

.foot .btn-face {
  position: absolute;
  margin-top: 10px;
  margin-left: 3px;
  font-size: 0.75rem;
}

.foot .selbox {
  float: left;
  height: 150px;
  margin-top: 48px;
  border-top: 1px solid #d9d9d9;
}

.foot .btn-icon {
  margin-top: 10px;
  margin-left: 3px;
  font-size: 0.75rem;
}

.show {
  display: block;
}

.hide {
  display: none;
}

.face-box {
  /* position: absolute; */
  /* top: 48px; */
  /* left: 0px; */
  /* right: 0px; */
  /* bottom: 0px; */
  padding: 0px 0px 0px 0px;
  overflow: hidden;
  width: 100%;
  margin: 0px auto;
  height: 100%;
}

.face-box li {
  width: 30px;
  float: left;
  padding: 6px 10px 0px 8px;
}

.btn {
  display: inline-block;
  vertical-align: top;
  font-size: 14px;
  line-height: 32px;
  margin-left: 5px;
  padding: 0 6px;
  background-color: #33df83;
  color: #fff;
  border-radius: 3px;
}

.btn-send {
  position: absolute;
  right: 0px;
  top: 8px;
}

.emjioBox {
  background: #fff;
  height: 150px;
  overflow: auto;
  text-align: left;
}
.emjioBox .emjio {
  padding: 0;
}
.emjioBox li {
  display: inline-block;
  width: 28px;
  height: 28px;
  line-height: 28px;
  text-align: center;
  cursor: pointer;
}
</style>
